//
//  JDBannerView.swift
//  DragonWallet
//
//  Created by volantPig on 2024/5/23.
//

enum JDPageLocation {
    case left
    case center
    case right
}

import UIKit
import PhotoSlider

protocol JDBannerViewDelegate: NSObjectProtocol {
    func bannerDidselected(banner: JDBannerView, index: Int)
}

class JDBannerView: JDBaseView {

    var _imgNameArray = [String]()
    var imgNameArray: [String] {
       set {
        _imgNameArray = newValue
            if pageControl != nil {
                if newValue.count > 1 {
                    pageControl?.isHidden = false
                } else {
                    pageControl?.isHidden = true
                }
            }
        }
        get {
            return _imgNameArray
        }
    }
    var scrollView: UIScrollView?
    var isPermitPress: Bool = false
    var pageControl: UIPageControl?//WJBPageControl?
    var pageLabel: UILabel?
    var placeHoldImageStr: String?
    var currentPage: Int = 0
    var location: JDPageLocation = .center
    var timer: Timer?
    var _needScrol: Bool = false
    var needScrol: Bool {
        set {
            _needScrol = newValue
            if newValue {
                if imgNameArray.count >= 2 {
                    if timer?.isValid ?? false {
                        timer?.invalidate()
                    }
                    timer = nil
                    self.timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)
                    RunLoop.main.add(self.timer!, forMode: RunLoop.Mode.common)
                }
            }
        }
        get {
            return _needScrol
        }
    }
    weak var myDelegate: JDBannerViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.createUIElements()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createUIElements() {
        scrollView = UIScrollView()
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.bounces = false
        
        if imgNameArray.count >= 2 {
            for index in 0...3 {
                let button = UIButton.init(type: UIButton.ButtonType.custom)
                button.frame = CGRect.init(x: CGFloat(index) * self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height)
                button.tag = index + 1000
                button.imageView?.contentMode = UIView.ContentMode.scaleToFill
                if index == 0 {
                    //设置图片
                } else if index == 1 {
                    
                } else if index == 2 {
                    
                }
                button.addTarget(self, action: #selector(buttonAction), for: UIControl.Event.touchUpInside)
                if self.isPermitPress {
                    button.isUserInteractionEnabled = false
                }
                scrollView?.addSubview(button)
            }
            scrollView?.contentSize = CGSize.init(width: CGFloat(3) * self.frame.size.width, height: self.frame.size.height)
            scrollView?.setContentOffset(CGPoint.init(x: self.frame.size.width, y: 0), animated: false)
        } else if imgNameArray.count == 1 {
            let button = UIButton.init(type: UIButton.ButtonType.system)
            button.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
            button.tag = 1000
            button.imageView?.contentMode = UIView.ContentMode.scaleToFill
            
            scrollView?.addSubview(button)
            scrollView?.contentSize = CGSize.init(width: self.frame.size.width, height: self.frame.size.height)
            scrollView?.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
            button.addTarget(self, action: #selector(buttonAction), for: UIControl.Event.touchUpInside)
            if self.isPermitPress {
                button.isUserInteractionEnabled = false
            }
        }
        scrollView?.delegate = self
        scrollView?.isPagingEnabled = true
        self.addSubview(scrollView!)
        scrollView?.snp.makeConstraints({ (make) in
            make.left.right.top.bottom.equalTo(self)
        })
        
        //设置页标
//        pageControl = UIPageControl.init()
//        pageControl?.frame = CGRect.init(x: 0, y: self.frame.size.height - 18, width: self.frame.size.width, height: 6)
//        pageControl?.setValue(UIImage.init(named: ""), forKey: "_pageImage")//"—_white"
//        pageControl?.setValue(UIImage.init(named: ""), forKey: "_currentPageImage")//"O_white"
//        pageControl?.numberOfPages = self.imgNameArray.count
//        pageControl?.currentPage = 0
//        pageControl?.isHidden = true
//        pageControl?.currentPageIndicatorTintColor = UIColor.black
//        pageControl?.pageIndicatorTintColor = UIColor.lightGray
//        self.addSubview(pageControl!)
        
        
        self.pageLabel = UILabel()
//        self.pageLabel?.frame = CGRectMake(self.frame.size.width-64, self.frame.size.height-48, 54, 38)
        self.pageLabel?.makeCorner(19)
        self.pageLabel?.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#FFFFFF"))
        self.addSubview(self.pageLabel!)
        self.pageLabel?.snp.makeConstraints({ make in
            make.right.equalTo(self).offset(-12)
            make.bottom.equalTo(self).offset(-10)
            make.size.equalTo(CGSizeMake(54, 38))
        })
        self.pageLabel?.backgroundColor = color("#333333").withAlphaComponent(0.8)
    }
    
    @objc func buttonAction() {
        print("点击轮播图")
//        var slider = PhotoSlider.ViewController(imageURLs: [URL.init(string: self.imgNameArray.first!)!,URL.init(string: self.imgNameArray.last!)!] )
//        slider.currentPage = self.currentPage
//        UIViewController.currentViewController()?.present(slider, animated: false, completion: nil)
        
//        self.myDelegate?.bannerDidselected(index: self.currentPage)
        self.myDelegate?.bannerDidselected(banner: self, index: self.currentPage)
    }
 
    func scrollViewReuseableDeal(scrollView: UIScrollView) {
        var placeImageName = "x" //默认图片
        if self.placeHoldImageStr != nil {
            placeImageName = self.placeHoldImageStr!
        }
        var button = self.viewWithTag(1001) as? UIButton
        if  button == nil {
            button = self.viewWithTag(1000) as? UIButton
        }
        
        if scrollView.contentOffset.x <= button!.frame.size.width/2.0 {
            //左滑
            self.currentPage -= 1
            if self.currentPage < 0 {
                self.currentPage = self.imgNameArray.count - 1
            }
        } else if scrollView.contentOffset.x >= button!.frame.size.width + self.frame.size.width/2.0 {
            self.currentPage += 1
            if self.currentPage > self.imgNameArray.count - 1 {
                self.currentPage = 0
            }
        }
        self.scrollView?.setContentOffset(CGPoint.init(x: self.frame.size.width, y: 0), animated: false)
        //取第一张图片
        let image1Name = self.imgNameArray[self.currentPage-1 >= 0 ? self.currentPage-1 : self.imgNameArray.count-1]
        let imgVleft = self.scrollView?.viewWithTag(1000) as? UIButton
        if image1Name.hasPrefix("http") {
            imgVleft?.kf.setBackgroundImage(with: URL.init(string: image1Name), for: UIControl.State.normal, placeholder: UIImage.init(named: placeImageName), options: nil, progressBlock: nil, completionHandler: { (result) in
            })
        } else {
            imgVleft?.downloadImage(image1Name)
        }
        
        //取第二张图片
        let image2Name = self.imgNameArray[self.currentPage]
        let imgVCenter = self.scrollView?.viewWithTag(1001) as? UIButton
        if image2Name.hasPrefix("http") {
            imgVCenter?.kf.setBackgroundImage(with: URL.init(string: image2Name), for: UIControl.State.normal, placeholder: UIImage.init(named: placeImageName), options: nil, progressBlock: nil, completionHandler: { (result) in
            })
        } else {
            imgVCenter?.downloadImage(image2Name)
        }
        
        //取第三张图片
        let image3Name = self.imgNameArray[(self.currentPage+1) > self.imgNameArray.count-1 ? 0 : self.currentPage+1]
        let imgVRight = self.scrollView?.viewWithTag(1002) as? UIButton
        
        if image3Name.hasPrefix("http") {
            imgVRight?.kf.setBackgroundImage(with: URL.init(string: image3Name), for: UIControl.State.normal, placeholder: UIImage.init(named: placeImageName), options: nil, progressBlock: nil, completionHandler: { (result) in
            })
        } else {
            imgVRight?.downloadImage(image3Name)
        }
        
        self.pageControl?.currentPage = self.currentPage
        self.pageLabel?.text = String.init(format: "%zd/%zd", (self.currentPage+1),self.imgNameArray.count)
    }

    @objc func autoScroll() {
        self.scrollView?.setContentOffset(CGPoint.init(x: self.frame.size.width * 2 , y: 0), animated: true)
    }
    
    func updateImgNameArray(imgArray: [String]) {
        for subV: UIView in self.scrollView!.subviews {
            if subV.tag >= 1000 && subV.tag <= 1100 {
                 subV.removeFromSuperview()
            }
        }
        self.imgNameArray = imgArray
        self.pageControl?.numberOfPages = self.imgNameArray.count

        let isNeedScrol = self.needScrol
        self.needScrol = isNeedScrol
        
        var placeImageName = "loading_placeholder"
        if self.placeHoldImageStr != nil {
            placeImageName = self.placeHoldImageStr!
        }
        if self.imgNameArray.count >= 2 {
            for index in 0...3 {
                let button = UIButton.init(type: .system)
                self.scrollView?.addSubview(button)
                button.frame = CGRect.init(x: CGFloat(index)*self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height)
                button.tag = index + 1000
                button.imageView?.contentMode = UIView.ContentMode.scaleToFill
                if index == 0 {
                    if self.imgNameArray.last?.hasPrefix("http") ?? false {
                        button.kf.setBackgroundImage(with: URL.init(string: self.imgNameArray.last!), for: UIControl.State.normal, placeholder: UIImage.init(named: placeImageName), options: nil, progressBlock: nil, completionHandler: { (result) in
                        })
                    } else {
                        button.downloadImage(self.imgNameArray.last!)
                    }
                } else if index == 1 {
                    if self.imgNameArray.first?.hasPrefix("http") ?? false {
                        button.kf.setBackgroundImage(with: URL.init(string: self.imgNameArray.first!), for: UIControl.State.normal, placeholder: UIImage.init(named: placeImageName), options: nil, progressBlock: nil, completionHandler: { (result) in
                        })
                    } else {
                        button.downloadImage(self.imgNameArray.first!)
                    }
                } else if index == 2 {
                    if self.imgNameArray[1].hasPrefix("http") {
                        button.kf.setBackgroundImage(with: URL.init(string: self.imgNameArray[1]), for: UIControl.State.normal, placeholder: UIImage.init(named: placeImageName), options: nil, progressBlock: nil, completionHandler: { (result) in
                        })
                    } else {
                        button.downloadImage(self.imgNameArray[1])
                    }
                }
                button.addTarget(self, action: #selector(buttonAction), for: UIControl.Event.touchUpInside)
                if self.isPermitPress {
                    button.isUserInteractionEnabled = false
                }
            }
            self.scrollView?.contentSize = CGSize.init(width: 3*self.frame.size.width, height: self.frame.size.height)
            self.scrollView?.setContentOffset(CGPoint.init(x: self.frame.size.width, y: 0), animated: false)
        } else if self.imgNameArray.count == 1 {
            let button = UIButton.init(type: .system)
            button.frame = CGRect.init(x: 0*self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height)
            button.tag = 1000
            button.imageView?.contentMode = UIView.ContentMode.scaleToFill
            if self.imgNameArray[0].hasPrefix("http") {
                button.kf.setBackgroundImage(with: URL.init(string: self.imgNameArray[0]), for: UIControl.State.normal, placeholder: UIImage.init(named: placeImageName), options: nil, progressBlock: nil) { (result) in
                }
            } else {
                button.downloadImage(self.imgNameArray[0])
            }
            self.scrollView?.addSubview(button)
            self.scrollView?.contentSize = CGSize.init(width: CGFloat(self.imgNameArray.count) * self.frame.size.width, height: self.frame.size.height)
            self.scrollView?.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
            button.addTarget(self, action: #selector(buttonAction), for: UIControl.Event.touchUpInside)
            if self.isPermitPress {
                button.isUserInteractionEnabled = false
            }
        }
        self.pageLabel?.text = String.init(format: "%zd/%zd", (self.currentPage+1),self.imgNameArray.count)
    }
    
    func pageControlStatus(hiddenStatus:Bool, location: JDPageLocation) {
        self.location = location
        self.pageControl?.isHidden = hiddenStatus
    }
    
    func setPageControlFrame() {
        let size  = self.pageControl?.size(forNumberOfPages: self.imgNameArray.count)
        if self.location == .left {
            self.pageControl?.frame = CGRect.init(x: 12, y: self.frame.size.height - 22, width: size!.width, height: 22)
        } else if self.location == .center {
            self.pageControl?.frame = CGRect.init(x: 0, y: self.frame.size.height - 22, width: self.frame.self.width, height: 22)
        } else if self.location == .right {
            self.pageControl?.frame = CGRect.init(x: self.frame.size.width - size!.width - 12, y: self.frame.self.height - 22, width: size!.width, height: 22)
        } else {
        }
    }
}

extension JDBannerView: UIScrollViewDelegate {
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        if self.imgNameArray.count >= 2 {
            self.scrollViewReuseableDeal(scrollView: scrollView)
        }
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if self.imgNameArray.count >= 2 {
            self.scrollViewReuseableDeal(scrollView: scrollView)
            if self.timer?.isValid ?? false {
                self.timer?.invalidate()
            }
            self.timer = nil
            self.timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)
            RunLoop.main.add(self.timer!, forMode: RunLoop.Mode.common)
        }
    }

}
